#检测2.python中保存的模型是否直接可以调用  并将提取的特征进行保存
import shutil
import os
import torch
import torch.nn as nn
from torchvision import models, transforms, datasets
import torch.utils.data
import numpy as np
import pandas as pd

device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")

data_dir = 'D:\\Program Files\\food101\\image'

test_dir = os.path.join(data_dir, 'test')

transform = transforms.Compose([
    transforms.CenterCrop(224),
    transforms.ToTensor(),
    transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
])

data_sets = {'test': datasets.ImageFolder(test_dir, transform)}


test_loader = torch.utils.data.DataLoader(data_sets['test'],
                                          batch_size=1,
                                          shuffle=False,
                                          num_workers=0)



def test_model(device, path, dataloader):
    model = torch.load(path)
    model.eval()
    total_preds = []
    for inputs, classes in dataloader:
        inputs = inputs.to(device)
        outputs = model(inputs)
        _, preds = torch.max(outputs.data, 1)
        total_preds.extend(preds)


    with open("D:\\Program Files\\food101\\result_test7.csv", 'a+') as f:
        for i in range(30):
            f.write("{},{}\n".format(i, total_preds[i]))


# model2适用
# data_saveouts=[]
# def test_model1(device, path, dataloader):
#     model = torch.load(path)
#     model.eval()
#     total_preds = []
#     for inputs, classes in dataloader:
#         inputs = inputs.to(device)
#         outputs = model(inputs)
#         print(outputs)
#         save_outputs=np.array(outputs)
#         data = pd.DataFrame(save_outputs)
#         data.to_csv('E:\\Desktop\\NSST\\1result_test14.csv', mode='a', header=False, index=None)




test_model(device, 'D:\\Program Files\\food101\\model1.pth', test_loader)

#test_model1(device, 'E:\\A数据迁移\\A_个人数据\\_aaaaaa挣点小钱\\510\\model2.pth', test_loader)

#测试成功，全部代码保存，直接可以调用